import { NInput, NSelect, NDatePicker } from "naive-ui";
import { h } from "vue";
import { ColumnsConfig } from "./type";
export const getBaseConf = (row: any, col: ColumnsConfig) => {
    return {
        value: row[col.key],
        placeholder: col.editConf?.placeholder || "",
        onUpdateValue: (value: any) => {
            row[col.key] = value;
        },
    };
};

const getShowOrEdit = (dom: any, col: ColumnsConfig, row: any, conf = {}) => {
    return defineComponent({
        props: {
            value: [String, Number],
            onUpdateValue: [Function, Array],
        },
        setup(props: any) {
            const isEdit = ref(false);
            const domRef: any = ref(null);
            const curValue = ref(props.value);
            function handleOnClick() {
                isEdit.value = true;
                nextTick(() => {
                    domRef.value.focus();
                });
            }
            function handleChange() {
                props.onUpdateValue(curValue.value);
                isEdit.value = false;
            }
            return () =>
                h(
                    "div",
                    {
                        style: "min-height: 22px",
                        onClick: handleOnClick,
                    },
                    isEdit.value
                        ? h(dom, {
                              ref: domRef,
                              value: curValue.value,
                              ...conf,
                              onUpdateValue: (v: any) => {
                                  curValue.value = v;
                              },
                              onChange: handleChange,
                              onBlur: handleChange,
                          })
                        : col.formateRender
                          ? col.formateRender(row)
                          : col.formateHtml
                            ? h("div", {
                                  innerHTML: col.formateHtml(row),
                              })
                            : props.value,
                );
        },
    });
};

export const getEditControl = (
    row: any,
    col: ColumnsConfig,
    dom: any,
    conf = {},
) => {
    return h(getShowOrEdit(dom, col, row, conf), {
        value: row[col.key],
        onUpdateValue(v: any) {
            row[col.key] = v;
        },
    });
};

export const controlsMap: any = {
    input: {
        dom: NInput,
        conf: () => {},
    },
    select: {
        dom: NSelect,
        conf: (col: ColumnsConfig) => {
            return { ...col.editConf };
        },
    },
    date: {
        dom: NDatePicker,
        conf: (col: ColumnsConfig) => {
            return {
                ...col.editConf,
                type: col.editConf?.type || "date",
            };
        },
    },
};
